﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Reflection;
using System.Runtime.Remoting;
using System.Windows.Forms;
using ToolUtil;
using zyconfig;

namespace zymain
{
    public partial class FrmTool : Form
    {
        private string uid;
        private AnchorStyles StopDock;
        private int gjm;
        private int fid;
        private string mids = string.Empty;

        public int Fid
        {
            get { return this.fid; }
            set { this.fid = value; }
        }
        public string UserID
        {
            get { return this.uid; }
            set { this.uid = value; }
        }

        public int Gjm
        {
            get { return this.gjm; }
            set { this.gjm = value; }
        }
        public FrmTool()
        {
            InitializeComponent();
            SetTitleCenter("北京邮电大学");
        }
        private void SetTitleCenter( string titleMsg)
        {
            string title = this.Text;
            Graphics g = this.CreateGraphics();
            Double startingPoint = (this.Width / 2) - (g.MeasureString(titleMsg, this.Font).Width / 2);
            Double widthOfASpace = g.MeasureString(" ", this.Font).Width;
            Double tmpWidth = title.Length;
            while ((tmpWidth + widthOfASpace) < startingPoint)
            {
                title += " ";
                tmpWidth += widthOfASpace;
            }
            this.Text= title + titleMsg;
        }
        /// <summary>
        /// 点击打开窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void MenuClicked(object sender, EventArgs e, int num,int id,string open)
        {
            //以下主要是动态生成事件并打开窗体
            //((sender as ToolStripMenuItem).Tag)强制转换
            ToolStripMenuItem item = (ToolStripMenuItem)sender;
            ObjectHandle t = Activator.CreateInstance("GdlisNet", "zymain." + item.Name);
            Form f = (Form)t.Unwrap();
            // 判断窗口是否打开
            if (!FrmConfig.checkChildFrmExist(item.Name))
            {
                this.fid = id;
                if (num == 0)
                {

                    f.ShowInTaskbar = false;
                    f.Owner = this;
                    if (string.IsNullOrEmpty(open))
                    {
                        f.WindowState = FormWindowState.Maximized;
                    }
                    f.Show();
                    f.Refresh();
                }
                else
                    f.ShowDialog();
            }
        }
        /// <summary>
        /// 添加子菜单
        /// </summary>
        /// <param name="text">要显示的文字，如果为 - 则显示为分割线</param>
        /// <param name="cms">要添加到的子菜单集合</param>
        /// <param name="callback">点击时触发的事件</param>
        /// <returns>生成的子菜单，如果为分隔条则返回null</returns>
        ToolStripMenuItem AddContextMenu(int id,string text, string curl, string img, ToolStripItemCollection cms, EventHandler callback,int ismenu)
        {
            if (text == "-")
            {
                ToolStripSeparator tsp = new ToolStripSeparator();
                cms.Add(tsp);
                return null;
            }
            else if (!string.IsNullOrEmpty(text))
            {
                ToolStripMenuItem tsmi = new ToolStripMenuItem(text);
                if (!string.IsNullOrEmpty(img))
                {
                    tsmi.Image = GetResourceImage(img);
                    tsmi.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
                    tsmi.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
                }
                tsmi.Font = new System.Drawing.Font("Microsoft YaHei UI", 11F);
                tsmi.Size = new System.Drawing.Size(90, 28);
                //tsmi.Padding = new System.Windows.Forms.Padding(5);
                tsmi.Name = curl;
                tsmi.Tag = text + "TAG";
                if (callback != null && ismenu==0)
                    tsmi.Click += callback;
                cms.Add(tsmi);
                using (DbOperHandler _open = new Common().Doh())
                {
                    if (ismenu > 0)
                    {
                        _open.Reset();
                        _open.SqlCmd = "select * from menu where  m_pid=" + id + " and m_id in ("+ this.mids+") order by m_sort";
                        DataTable dt = _open.GetDataTable();
                        if (dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            { 
                                int mid = Convert.ToInt32(dt.Rows[i]["m_id"].ToString());
                                string open = dt.Rows[i]["m_open"].ToString().Trim();
                                AddContextMenu(mid, dt.Rows[i]["m_title"].ToString(), dt.Rows[i]["m_url"].ToString(), dt.Rows[i]["m_icon"].ToString(), tsmi.DropDownItems, delegate (object sender1, EventArgs e1) { MenuClicked(sender1, e1, 0, mid, open); }, Convert.ToInt32(dt.Rows[i]["M_ISMENU"].ToString()));
                            }
                        }
                    }
                } 
                return tsmi;
            }
            return null;
        }
        /// <summary>
        /// 定义一个资源文件名 资源文件名 = 工程的默认命名空间+文件名(不带扩展名)
        /// </summary>
        private string PublicResourceFileName = "zymain.Properties.Resources";

        public System.Object ReadFromResourceFile(String resName)
        {
            try
            {
                Assembly myAssembly;
                myAssembly = Assembly.GetExecutingAssembly();
                System.Resources.ResourceManager rm = new
                System.Resources.ResourceManager(PublicResourceFileName, myAssembly);
                return rm.GetObject(resName);
            }
            catch (Exception ex)
            {
                return null;

            }
        }
        public Bitmap GetResourceImage(String name)
        {
            Object tempbitmap = null;
            tempbitmap = ReadFromResourceFile(name);
            if (tempbitmap.GetType().Equals(typeof(Bitmap)))
            {
                return (Bitmap)tempbitmap;
            }
            return null;
        }
        private void FrmTool_Load(object sender, EventArgs e)
        {
            using (DbOperHandler _open = new Common().Doh())
            {
                _open.Reset();
                _open.ConditionExpress = "代码=" + UserID;
                string mid = _open.GetField("系统用户", "菜单").ToString().Trim();
                foreach (string str in mid.Split(','))
                {
                    mids += "'" + str + "',";
                }
                mids = mids.Substring(0, mids.Length - 1);
            }
            this.StopDock = AnchorStyles.Top;
            this.Width = Screen.PrimaryScreen.Bounds.Width;
            this.Location = new Point(0, 0);
            this.TopMost = true;
            Timer checkDockTimer = new Timer();
            checkDockTimer.Tick += new EventHandler(StopRectTimer_Tick);
            checkDockTimer.Interval = 100;
            checkDockTimer.Enabled = true;
        }

        
        private void StopRectTimer_Tick(object sender, EventArgs e)
        {
            //如果鼠标在窗体上，则根据停靠位置显示整个窗体
            if (this.Bounds.Contains(Cursor.Position))
            {
                switch (this.StopDock)
                {
                    case AnchorStyles.Top:
                        this.Location = new Point(this.Location.X, 0);
                        break;
                    case AnchorStyles.Bottom:
                        this.Location = new Point(this.Location.X, Screen.PrimaryScreen.Bounds.Height - this.Height);
                        break;
                    case AnchorStyles.Left:
                        this.Location = new Point(0, this.Location.Y);
                        break;
                    case AnchorStyles.Right:
                        this.Location = new Point(Screen.PrimaryScreen.Bounds.Width - this.Width, this.Location.Y);
                        break;
                }
            }
            else  //如果鼠标离开窗体，则根据停靠位置隐藏窗体，但须留出部分窗体边缘以便鼠标选中窗体
            {
                switch (this.StopDock)
                {
                    case AnchorStyles.Top:
                        this.Location = new Point(this.Location.X, (this.Height - 3) * (-1));
                        break;
                    case AnchorStyles.Bottom:
                        this.Location = new Point(this.Location.X, Screen.PrimaryScreen.Bounds.Height - 5);
                        break;
                    case AnchorStyles.Left:
                        this.Location = new Point((-1) * (this.Width - 3), this.Location.Y);
                        break;
                    case AnchorStyles.Right:
                        this.Location = new Point(Screen.PrimaryScreen.Bounds.Width - 2, this.Location.Y);
                        break;
                }
            }
        }

        private void FrmTool_Closing(object sender, FormClosingEventArgs e)
        {
            DialogResult result;
            result = MessageBox.Show("确定退出吗？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                Application.ExitThread();
                Application.Exit();
                Process.GetCurrentProcess().Kill();
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void FrmTool_Shown(object sender, EventArgs e)
        {
            List<Menu> modelList = new List<Menu>();
            DataTable dt = new DataTable();
            using (DbOperHandler _open = new Common().Doh())
            {
                _open.Reset();
                string sql = "select * from menu where M_PID=0 and M_ID in("+ mids +") order by m_pid,m_sort";
                _open.SqlCmd = sql;
                dt = _open.GetDataTable();
                ToolStripMenuItem subItem = new ToolStripMenuItem();
                foreach (DataRow dr in dt.Rows)
                {
                    subItem = AddContextMenu(0,"-", "", "", toolStrip1.Items, null,0);
                    subItem = AddContextMenu(Convert.ToInt32(dr["M_ID"].ToString()),dr["M_TITLE"].ToString(), dr["M_URL"].ToString(), dr["M_ICON"].ToString(), toolStrip1.Items, null, Convert.ToInt32(dr["M_ISMENU"].ToString()));
                    DataTable dt1 = new DataTable();
                    _open.Reset();
                    string sql1 = "select * from menu where  m_pid=" + dr["M_ID"].ToString() + " and M_ID in(" + mids + ") order by m_sort";
                    //Console.WriteLine(sql1);
                    _open.SqlCmd = sql1;
                    dt1 = _open.GetDataTable();
                    if (dt1.Rows.Count > 0)
                    {
                        for (int i = 0; i < dt1.Rows.Count; i++)
                        {
                            int id = Convert.ToInt32(dt1.Rows[i]["m_id"].ToString());
                            string openfs = dt1.Rows[i]["m_open"].ToString().Trim();
                            AddContextMenu(id,dt1.Rows[i]["m_title"].ToString(), dt1.Rows[i]["m_url"].ToString(), dt1.Rows[i]["m_icon"].ToString(), subItem.DropDownItems, delegate (object sender1, EventArgs e1) { MenuClicked(sender1, e1, 0, id, openfs); }, Convert.ToInt32(dt1.Rows[i]["M_ISMENU"].ToString()));
                        }
                    }
                    
                }
                //subItem = AddContextMenu("-", "", "", toolStrip1.Items, null);
                //subItem = AddContextMenu("修改密码", "FrmMpass", "New_Pass", toolStrip1.Items, delegate (object sender1, EventArgs e1) { MenuClicked(sender1, e1, 1); });
                //subItem = AddContextMenu("-", "", "", toolStrip1.Items, null);
                //subItem = AddContextMenu("系统设置", "FrmConfig", "New_Setting", toolStrip1.Items, delegate (object sender1, EventArgs e1) { MenuClicked(sender1, e1, 1); });
                subItem = AddContextMenu(0,"-", "", "", toolStrip1.Items, null,0);
                subItem = AddContextMenu(0,"退出系统", "", "New_Exit", toolStrip1.Items, new EventHandler(ExitClicked),0);
            }
        }

        void ExitClicked(object sender, EventArgs e)
        {
            DialogResult result;
            result = MessageBox.Show("确定退出吗？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (result == DialogResult.OK)
            {
                Process.GetCurrentProcess().Kill();
                //Application.ExitThread();
                //Application.Exit();
            }
        }
    }
}
